<template>
	<view>
		<!-- #ifdef MP-ALIPAY -->
		<!-- #endif -->
		<view v-if="isCanUse">
			<view>
				<view class='header'>
					<image :src='avatarUrl'></image>
				</view>
				<view class='content'>
					<view>申请获取以下权限</view>
					<text>获得你的公开信息(昵称:{{nickName}}，头像、地区等)</text>
				</view>

				<view v-if="isShowBind" class="contenr flex flex-direction align-center">
					<input placeholder="手机号" v-model="mobile" />
					<view class="sms-inp flex align-center justify-between">
						<input placeholder="短信验证码" v-model="mobileSMS" />
						<view @click="sms" class="sms-btn flex align-center justify-center">
							<text v-if="!isStopwatch">获取验证码</text>
							<text v-else>{{time}}S后重发</text>
						</view>
					</view>
				</view>
				<!-- <button class='bottom' type='primary' open-type="getUserInfo" withCredentials="true" lang="zh_CN" @getuserinfo="appLoginWx">
					授权登录
				</button> -->
				<button v-if="isShowAli" class='bottom' type='primary' withCredentials="true" lang="zh_CN" open-type="getAuthorize" @getAuthorize="aligetProvider" @error="onAuthError" scope='userInfo'>
					授权登录
				</button>
				<button v-else class='bottom' type='primary'  @click="saveGetOAuthRegister">
					登录
				</button>
			</view>
		</view>

	</view>
</template>

<script>
	var api = require('@/components/api.js');
	export default {
		data() {
			return {
				sessionKey: '',
				encryptedData:'',
				iv:'',
				openId: '',
				nickName: '',
				avatarUrl: '',
				isCanUse: uni.getStorageSync('isCanUse') || true, //默认为true
				mobile: '',
				mobileSMS: '',
				mobileCode: '',
				unionid:'',
				isShowBind: false,
				isStopwatch: false,
				isShowAli:true,
				time: 60
			}
		},
		onLoad() { //默认加载
			this.wxGetUserInfo();
			// this.login();
		},
		methods: {
			onAuthError(err){
				console.log('err',err);
			},
			
			aligetProvider(){
				let _this = this;
				uni.getProvider({
				  service: 'oauth',
				  success: function (res) {
				    console.log(res.provider)
					if (~res.provider.indexOf('alipay')) {
						uni.setStorageSync('isCanUse', false); //记录是否第一次授权  false:表示不是第一次授权
						_this.isShowAli = true
						_this.login()
					}
				  }
				});
			},
			
			
			//第一授权获取用户信息===》按钮触发
			wxGetUserInfo() {
				
				let _this = this;
				uni.getUserInfo({
					provider: 'alipay',
					success: function(infoRes) {
						console.log('wxGetUserInfo:' + JSON.stringify(infoRes))
						_this.nickName = infoRes.userInfo.nickName;
						_this.avatarUrl = infoRes.userInfo.avatarUrl;
						_this.iv = infoRes.iv;
						_this.encryptedData = infoRes.encryptedData;
						try {
							
							var user = {}
							user.nick_name = _this.nickName
							user.avatar = _this.avatarUrl
							uni.setStorageSync('isCanUse', false); //记录是否第一次授权  false:表示不是第一次授权
							_this.isShowAli = true
							_this.login()
							
						} catch (e) {}
					},
					fail(res) {
						uni.showToast({
							title:'请点击授权登陆'
						})
						console.log('fail'+JSON.stringify(res))
					},
					complete(res) {
						console.log('wxGetUserInfo->complete'+JSON.stringify(res))
					}
				});
				
			},
			getUnionId:function() {//sessionKey,encryptedData,iv
			    if(this.encryptedData =='' || this.iv ==''){
					uni.showToast({
						title:'授权失败，请重新授权'
					})
					return;
				}
				console.log('sessionKey:'+this.sessionKey+' encryptedData:'+this.encryptedData+' iv:'+this.iv)
				api.post({
					url: 'User/DecryptSensitiveData?sessionKey='+this.sessionKey+'&encryptedData='+this.encryptedData+'&iv='+this.iv,
					data: {
						// sessionKey: sessionKey,
						// encryptedData: encryptedData,
						// iv: iv,
					},
					success: (res) => {
						console.log('getUnionId:'+JSON.stringify(res))
						if (res.ErrCode == 0) {
							this.unionid = res.Response
							if(this.unionid != ''){
							  this.getOAuthConfirm()	
							}
							
						}
					}
				});
			},

			//登录
			login() {
				// this.wxGetUserInfo();
				let _this = this;
				uni.showLoading({
					title: '登录中...'
				});
				
				// 1.zfb获取登录用户code
				uni.login({
					provider: 'alipay',
					scopes:"auth_user",
					success: function(loginRes) {
						console.log(JSON.stringify(loginRes))
						console.log('_this.isCanUse',_this.isCanUse)
						let code = loginRes.code;
						if (!_this.isCanUse) {
							//非第一次授权获取用户信息
							uni.getUserInfo({
								provider: 'alipay',
								success: function(infoRes) {
									console.info('uniapp用户基础信息',infoRes)
									console.log(JSON.stringify(infoRes))
									//获取用户信息后向调用信息更新方法
									_this.nickName = infoRes.userInfo.nickName; //昵称
									_this.avatarUrl = infoRes.userInfo.avatarUrl; //头像
									_this.iv = infoRes.iv;
									_this.encryptedData = infoRes.encryptedData;
								}
							});
						}
						console.log('code',code)
						//return;
						//2.将用户登录code传递到后台置换用户SessionKey、OpenId等信息
						api.post({
							url: 'AliAuth/auth?auth_code='+code,
							data: {
								
							},
							success: (res) => {
								console.log('code:'+JSON.stringify(res))
								var data = res.Response
								if (res.ErrCode == 0) {
									_this.openId = data.oauth_openid
									uni.setStorageSync('buyer_id', _this.openId)
									//强制页面重载，跳转到首页

									//uni.setStorageSync('upload', 1)
									//uni.setStorageSync('login', 1)
									//uni.setStorageSync('token', data.oauth_access_token)
									//uni.setStorageSync('user', data)
									
									//setTimeout((e => {
									//	uni.navigateBack();
									//}), 500);
									
									
									
									_this.getOAuthConfirm()
									//_this.wxGetUserInfoSecond()
									
								}
								uni.hideLoading();
								/**/
							}
						});
					},
				});
			},
			wxGetUserInfoSecond() {
				let _this = this;
				uni.getUserInfo({
					provider: 'alipay',
					success: function(infoRes) {
						console.log('wxGetUserInfo:' + JSON.stringify(infoRes))
						_this.nickName = infoRes.userInfo.nickName;
						_this.avatarUrl = infoRes.userInfo.avatarUrl;
						_this.iv = infoRes.iv;
						_this.encryptedData = infoRes.encryptedData;
						try {
						_this.getUnionId()
							
						} catch (e) {}
					},
					fail(res) {
						console.log('fail'+JSON.stringify(res))
					},
					complete(res) {
						console.log('complete'+JSON.stringify(res))
					}
				});
			},
			getOAuthConfirm() {
				api.get({
					url: 'User/GetOAuthConfirm',
					data: {
						// oauth_openid: this.openId,
						oauth_unionid: this.openId,
						oauth_name: 'alipay',
					},
					success: (res) => {
						console.log('getOAuthConfirm:'+JSON.stringify(res))
						if (res.ErrCode == 0) {
							uni.setStorageSync('user', res.Response)
							//强制页面重载，跳转到首页
							uni.reLaunch({
								url: '/pages/index/index'
							});
						} else {
							this.isShowBind = true;
							this.isShowAli = false;
							uni.showToast({
								title: '请绑定手机号码'
							})
						}
					}
				});
			},
			//向后台更新信息
			saveGetOAuthRegister() {
				// this.wxGetUserInfo()
				let _this = this;
				if (!_this.mobile) {
					uni.showToast({
						title: '请输入手机号码'
					})
					return;
				}
				if (!_this.mobileSMS) {
					uni.showToast({
						title: '请输入验证码'
					})
					return;
				}
				if (_this.mobileSMS != _this.mobileCode) {
					uni.showToast({
						title: '验证码错误'
					})
					return;
				}
				
				api.get({
					url: 'User/GetOAuthRegister', //服务器端地址
					data: {
						nick_name: _this.nickName,
						// oauth_openid: _this.openId,
						oauth_unionid: _this.openId,
						avatar: _this.avatarUrl,
						oauth_name: 'alipay',
						mobile: _this.mobile,
						password: '999999'
					},
					success: (res) => {
						if (res.ErrCode == 0) {
							uni.setStorageSync('user', res.Response)
							uni.reLaunch({ //信息更新成功后跳转到小程序首页
								url: '/pages/index/index'
							});
						}else if(res.ErrCode == 2){
							uni.showToast({
								title:'授权失败'
							})
						}
					}

				});
			},

			/***********************************/
			sms: function() {
				if (this.isStopwatch) {
					return;
				}
				if (!this.mobile) {
					uni.showToast({
						icon: 'none',
						title: '请输入手机号码'
					})
					return;
				}
				api.get({
					url: 'User/GetOAuthRegisterCode',
					data: {
						mobile: this.mobile
					},
					success: data => {
						console.info(JSON.stringify(data))
						if (data.ErrCode == 0) {
							this.mobileCode = data.Response.code
							uni.showToast({
								icon: 'none',
								title: '已发送'
							})
						}
					}
				});
				this.isStopwatch = true
				this.setMyTime();
			},
			setMyTime: function() {
				console.log(this.time)
				if (this.time > 0) {
					this.time = --this.time
					setTimeout(() => this.setMyTime(), 1000);
				} else {
					this.time = 60
					this.isStopwatch = false
				}
			}

			/***********************************/
		},

	}
</script>

<style lang="scss" scoped>
	.header {
		margin: 90rpx 0 90rpx 50rpx;
		border-bottom: 1px solid #ccc;
		text-align: center;
		width: 650rpx;
		height: 200rpx;
		line-height: 450rpx;
	}

	/****height: 300rpx;***/
	.header image {
		width: 200rpx;
		height: 200rpx;
	}

	.content {
		margin-left: 50rpx;
		margin-bottom: 90rpx;
	}

	.content text {
		display: block;
		color: #9d9d9d;
		margin-top: 40rpx;
	}

	.bottom {
		border-radius: 80rpx;
		margin: 70rpx 50rpx;
		font-size: 35rpx;
		background-color: $btn-bground;
	}

	/******验证******/
	.sms-btn {
		width: 178upx;
		border-left: 1upx solid #999999;
	}

	.sms-btn text {
		font-size: 26upx;
		color: #999999;
	}

	.sms-inp {
		width: 660upx;
		height: 70upx;
		background-color: #f0f0f0;
		border-radius: 35upx;
		margin-bottom: 30upx;
	}

	.sms-inp {
		padding-left: 42upx;
		box-sizing: border-box;
	}

	.contenr>input {
		width: 660upx;
		height: 70upx;
		background-color: #f0f0f0;
		border-radius: 35upx;
		padding-left: 42upx;
		margin-bottom: 30upx;
	}

	/******验证\******/
</style>
</style>
